package org.ravenhearte.engine.gui;

import org.ravenhearte.engine.input.InputEvent;
import org.ravenhearte.engine.input.InputEventManager;
import org.ravenhearte.engine.input.InputEvent.EventType;
import org.ravenhearte.engine.input.InputEventManager.Queue;

import com.jme.renderer.ColorRGBA;
import com.jme.scene.shape.Quad;
import com.jme.scene.state.ClipState;
import com.jme.system.DisplaySystem;

public class GUIContainer extends GUIElement {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8445106594813386898L;
	
	private GUITitleBar titleBar;

	public GUIContainer(String name, ColorRGBA color, int width, int height) {
		super("Container " + name);

		mesh = new Quad(this.name + "'s Mesh", width, height);
		mesh.setSolidColor(color);
		
		ClipState clipState = DisplaySystem.getDisplaySystem().getRenderer().createClipState();
        clipState.setEnableClipPlane( ClipState.CLIP_PLANE0, true );
        clipState.setEnableClipPlane( ClipState.CLIP_PLANE1, true );
        clipState.setEnableClipPlane( ClipState.CLIP_PLANE2, true );
        clipState.setEnableClipPlane( ClipState.CLIP_PLANE3, true );
        setRenderState( clipState );

		attachChild(mesh);
		
		loadEvents();
	}
	
	public void addTitleBar(String text, ColorRGBA color, int height) {
		titleBar = new GUITitleBar(this, text, color, (int) mesh.getWidth(), height);
		titleBar.setLocalTranslation(0, (mesh.getHeight() / 2) - (height / 2), 0);
		attachChild(titleBar);
		titleBar.setZOrder(getZOrder() -3, true);
		titleBar.setZOrder(getZOrder() -2);
		
		InputEvent evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.CUSTOM;
		evnt.textId = "Move " + name;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);
	}

	@Override
	public boolean onEvent(InputEvent ev) {
		switch (ev.type) {
		case CUSTOM:
			if (ev.textId.contentEquals("MousePress " + name + "'s Mesh")) {
				return true;
			}
			else if (ev.textId.contentEquals("Move " + name)) {
				int newX = (int) (localTranslation.x + ev.delta);
				int newY = (int) (localTranslation.y + ev.delta2);
				
				setLocalTranslation(newX, newY, 0);
				
				InputEvent evnt = new InputEvent();
				evnt.parent = this;
				evnt.type = EventType.CUSTOM;
				evnt.textId = "GUI Refresh";
				InputEventManager.eM.generateEvent(evnt);
				return true;
			}
			break;
		}
		return false;
	}
	
	private void loadEvents() {
		InputEvent evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.CUSTOM;
		evnt.textId = "MousePress " + name + "'s Mesh";
		evnt.id = 0;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);
	}

	@Override
	public void unloadEvents() {
		if(titleBar != null) {
			titleBar.unloadEvents();
		}
		InputEventManager.eM.unregisterEvents(this);
	}
}